package com.copa.l203;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author copa
 * @createDate 2022-06-08 21:16
 * @function 迭代法
 */
public class Test1 {

    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        // 虽然下面思路是想对了，但是没想到在这里遭殃...
//        ListNode pre = new ListNode();
//        pre.next = head;
        // 准确来说这里指向dummy即可
        ListNode pre = dummy;
        while (head != null) {
            if (head.val == val) {
                pre.next = head.next;
                head = head.next;
                continue;
            }
            pre = head;
            head = head.next;
        }

        return dummy.next;
    }

    public ListNode removeElements2(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        Queue<Integer> queue = new LinkedList<>();
        while (head != null) {
            if (head.val != val) {
                queue.add(head.val);
            }
            head = head.next;
        }
        if (queue.size() == 0) {
            return null;
        }
        ListNode listNode = new ListNode(queue.poll());
        ListNode result = listNode;
        while (queue.size() > 0) {
            listNode.next = new ListNode(queue.poll());
            listNode = listNode.next;
        }
        return result;
    }

    public static void main(String[] args) {
//        ListNode head = new ListNode(1);
//        head.next = new ListNode(2);
//        head.next.next = new ListNode(6);
//        head.next.next.next = new ListNode(3);
//        head.next.next.next.next = new ListNode(4);
//        head.next.next.next.next.next = new ListNode(5);
//        head.next.next.next.next.next.next = new ListNode(6);
        ListNode head = new ListNode(7);
        head.next = new ListNode(7);
        head.next.next = new ListNode(7);
        head.next.next.next = new ListNode(7);
        ListNode result = new Test1().removeElements(head, 7);
        while (result != null) {
            System.out.print(result.val + "\t");
            result = result.next;
        }
    }
}
